module CalendarHelper
    
  def select_day_events(day)  
    array = []
    time = Time.now + day.days
  
    @events.each do |ev|
      if (ev.start.day == time.day) && (ev.start.month == time.month) && (ev.start.year == time.year)
        array << ev
      end
    end
    return array
  end
  
  
  def write_month (time)
    current_time = time.to_s
    current_time = current_time.split(" ");
    return @month = current_time[1]
  end
  
  def query_calendar_events
    
    @events = select_events_in_range(6)
    
    @today = select_day_events(0)
    @tomorrow = select_day_events(1)
    @day_after_tomorrow = select_day_events(2)
    @day_after_after_tomorrow = select_day_events(3)
    @day_after_after_after_tomorrow = select_day_events(4)
    @day_after_after_after_after_tomorrow = select_day_events(5)
    @day_after_after_after_after_after_tomorrow = select_day_events(6)
    
   # NOTICE!! param main is just a flag that comes form the show.html, shows if it is an ajax remote link or not.
    is_it_not_remote = unless params[:main] != nil then true else false end
     
    if(is_it_not_remote)
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @seminar }
      end
    else
      render :partial => 'calendar/templates/in_a_week'
    end
  end


  # this is a workaround mehtod since the query in the show method does not work!!!. Is not comparing the time stamps!
  def select_events_in_range(offset)
    current_time = Time.now
    add_time = (60 * 60 * 24)*offset
    in_a_time = current_time + add_time
 
    announcements = Announcement.find_by_sql("SELECT * FROM announcements WHERE announcement_type != 'class_room' order by start asc")
    counter = 0
    result = []
    announcements.each do |a|
      #Notice that here i change the time to integers since is much easier to check than the time object
      if(offset == 1) 
        if((a.end >= current_time) && (a.end.day == current_time.day))
          result[counter] = a unless result.length >= 6
          counter+=1
        end
      elsif((a.end >= current_time) && (a.end <= in_a_time)) 
        result[counter] = a unless result.length >= 6
        counter+=1
      end
    end
    return result
  end
  
end